package com.zky.dao;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zky.domain.po.Cattle;
import com.zky.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

//奶牛持久层
@Component
@RequiredArgsConstructor
public class CattleDao {

    private final StringRedisTemplate stringRedisTemplate;
    private final RedisUtil redisUtil;

    public List<Cattle> getAllCattle() {
        List<Cattle> cattle = redisUtil.getListForSet("cattle", Cattle.class);
        return cattle;
    }

    public void addCattle(Cattle cattle) {
        redisUtil.addForSet("cattle", cattle);
    }

    //批量添加
    public void addCattleBatch(List<Cattle> cattles) {
        redisUtil.addForSet("cattle", JSONUtil.toJsonStr(cattles));
    }

    public void deleteCattleById(Long id) {
        List<Cattle> allCattle = getAllCattle();
        allCattle.removeIf(cattle -> cattle.getId().equals(id));
        //删除整个key
        stringRedisTemplate.delete("cattle");
        addCattleBatch(allCattle);

    }

    public Cattle getCattleById(String id) throws Exception {
        for (Cattle cattle : getAllCattle()) {
            if (cattle.getId().equals(id)) {
                return cattle;
            }
        }
        throw new Exception("没有对应的奶牛");
    }


}
